import Vue from 'vue'
// 导入路由模块
import VueRouter from 'vue-router'

// 导入所需组件
// import Login from '@/components/Login.vue'
// import Welcome from '@/components/Welcome.vue'
// import Home from '@/components/Home.vue'
const Login = () => import(/* webpackChunkName: "login_home_welcome" */ '@/components/Login.vue')
const Home = () => import(/* webpackChunkName: "login_home_welcome" */ '@/components/Home.vue')
const Welcome = () =>
  import(/* webpackChunkName: "login_home_welcome" */ '@/components/Welcome.vue')

// import User from '@/components/user/User.vue'
// import Rights from '@/components/power/Rights.vue'
// import Roles from '@/components/power/Roles.vue'
const User = () => import(/* webpackChunkName: "user_rights_roles" */ '@/components/user/User.vue')
const Rights = () =>
  import(/* webpackChunkName: "user_rights_roles" */ '@/components/power/Rights.vue')
const Roles = () =>
  import(/* webpackChunkName: "user_rights_roles" */ '@/components/power/Roles.vue')

// import Cate from '@/components/goods/Cate.vue'
// import Params from '@/components/goods/Params.vue'
const Cate = () => import(/* webpackChunkName: "cate_params" */ '@/components/goods/Cate.vue')
const Params = () => import(/* webpackChunkName: "cate_params" */ '@/components/goods/Params.vue')

// import List from '@/components/goods/List.vue'
// import Add from '@/components/goods/Add.vue'
const List = () => import(/* webpackChunkName: "list_add" */ '@/components/goods/List.vue')
const Add = () => import(/* webpackChunkName: "list_add" */ '@/components/goods/Add.vue')

// import Order from '@/components/order/Order.vue'
// import Report from '@/components/report/Report.vue'
const Order = () => import(/* webpackChunkName: "order_report" */ '@/components/order/Order.vue')
const Report = () => import(/* webpackChunkName: "order_report" */ '@/components/report/Report.vue')

// 将 路由模块 安装到 Vue 上
Vue.use(VueRouter)

// 路由规则数组
const routes = [
  // 重定向路由规则
  { path: '/', redirect: '/login' },
  // 路由规则
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: Welcome },
      { path: '/users', component: User },
      { path: '/rights', component: Rights },
      { path: '/roles', component: Roles },
      { path: '/categories', component: Cate },
      { path: '/params', component: Params },
      { path: '/goods', component: List },
      { path: '/goods/add', component: Add },
      { path: '/orders', component: Order },
      { path: '/reports', component: Report }
    ]
  }
]

// 路由实例对象
const router = new VueRouter({
  routes
})

// 给路由对象添加 beforEach 全局前置守卫
router.beforeEach((to, from, next) => {
  // 判断用户是否访问登录页面(直接放行)
  if (to.path === '/login') return next()
  // 判断用户是否登录过
  const token = window.sessionStorage.getItem('token')
  // 没登录过 强制跳转登录页面
  if (!token) return next('/login')
  // 最后
  next()
})

// 默认导出路由实例对象
export default router
